<!--
 * @Author: wangming
 * @Date: 2020-09-09 14:04:55
 * @LastEditors: wangming
 * @LastEditTime: 2022-04-01 10:17:25
 * @Description:添加类别按钮
-->
<template>
  <el-dialog :visible="showVisible" center :show-close="false" width="750px">
    <div class="b g3 f16 tl" slot="title">
      <div class="ks-row-between pl15 pr15">
        <span>{{
          isNew ? $t("sys.initiating_entrustment") : $t("sys.edit_delegation")
        }}</span>
        <span class="el-icon-close g9 f26 poi" @click="handleCancel"></span>
      </div>
    </div>

    <el-form class="pl30 pr30" :model="formData" ref="form" label-width="100px">
      <el-form-item
        :label="$t('sys.person')"
        prop="userId"
        :rules="[
          {
            required: true,
            message: $t('sys.please_select_person'),
            trigger: 'change',
          },
        ]"
      >
        <div @click.stop="handleAssigneeSelect">
          <el-input
            :value="formData.userName"
            :placeholder="$t('sys.please_select_person')"
          />
        </div>
      </el-form-item>

      <el-form-item
        prop="dateTimeRange"
        :label="$t('sys.entrusted_time')"
        :rules="[
          {
            required: true,
            message: $t('sys.select_agent_start_time_end_time'),
            trigger: 'change',
          },
        ]"
      >
        <el-date-picker
          v-model="formData.dateTimeRange"
          type="datetimerange"
          :range-separator="$t('sys.to')"
          :clearable="false"
          :picker-options="pickerOptions"
          format="yyyy-MM-dd HH:mm"
          value-format="yyyy-MM-dd HH:mm"
          :default-time="['00:00:00', '23:59:00']"
          :start-placeholder="$t('sys.select_agent_start_time')"
          :end-placeholder="$t('sys.select_agent_end_time')"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item
        prop="processKeys"
        :label="$t('sys.delegate_type')"
        :rules="[
          {
            required: true,
            message: $t('sys.select_delegate_type'),
            trigger: 'change',
          },
        ]"
      >
        <el-checkbox
          :indeterminate="isIndeterminate"
          v-model="checkAll"
          @change="handleCheckAllChange"
          >{{ $t("sys.check_all") }}</el-checkbox
        >
        <div style="margin: 15px 0"></div>
        <el-checkbox-group
          v-model="formData.processKeys"
          @change="handleCheckedProcessChange"
        >
          <el-checkbox
            v-for="process in processList"
            :label="process.key"
            :key="process.key"
            ><span
              :title="process.name + '（' + process.key + '）'"
              class="limit"
              >{{ process.name + "（" + process.key + "）" }}</span
            ></el-checkbox
          >
        </el-checkbox-group>
      </el-form-item>
    </el-form>
    <div slot="footer" class="tr">
      <el-button @click="handleCancel">{{ $t("sys.cancel") }}</el-button>
      <el-button type="primary" @click="submit">{{
        $t("sys.confirm")
      }}</el-button>
    </div>

    <select-modal
      itemRadio
      :title="$t('sys.select_person')"
      :autoClose="false"
      ref="SelectAssigneeModal"
      :treeData="orgTree"
      :treeNodeChange="handleSelectAssigneeNodeChange"
      @ok="handleAssigneeChange"
    >
    </select-modal>
  </el-dialog>
</template>

<script>
import SelectModal from "@/components/SelectModal";
import { arrayToTree } from "@/utils/util";

import { getHmprocessList } from "@/apis/paas/HmProcessController.js";
import {
  putHmtaskdelegate,
  postHmtaskdelegate,
} from "@/apis/paas/HmTaskDelegateController.js";
import { getHmuserPageListwithpermission } from "@/apis/paas/HmUserController.js";
import { getHmorgList } from "@/apis/paas/HmOrgController.js";

export default {
  name: "AuthModal",
  components: {
    SelectModal,
  },
  data() {
    return {
      showVisible: false,
      checkedProcess: [],
      processList: [],
      orgTree: [],
      checkAll: false,
      isIndeterminate: true,
      formData: {
        processKeys: [],
      },
      pickerOptions: {
        disabledDate(time) {
          // return time.getTime() < Date.now()
          return time.getTime() < Date.now() - 8.64e7;
        },
      },
      callback: () => {},
      validator: (rule, value, callback) => {
        callback();
      },
    };
  },

  computed: {
    isNew() {
      return !this.formData.id;
    },
  },
  mounted() {
    this.loadOrgData();
  },

  methods: {
    async addForm(record = {}) {
      // this.listData = await getHmorgList();
      this.loadOrgData();
      this.processList = await getHmprocessList({ activated: true });
      this.formData = {
        ...record,
        processKeys: [],
      };
      this.showVisible = true;
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
    },

    async editForm(record) {
      this.loadOrgData();
      this.processList = await getHmprocessList({ activated: true });
      this.formData = { ...record };
      this.formData.dateTimeRange = [
        new Date(record.startAt).format("yyyy-MM-dd hh:mm"),
        new Date(record.endAt).format("yyyy-MM-dd hh:mm"),
      ];
      this.showVisible = true;
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
    },

    /**
     * 加载部门数据
     */
    loadOrgData() {
      if (this.orgTree?.length) return;
      getHmorgList().then((res) => {
        this.orgTree = arrayToTree(res);
      });
    },
    handleAssigneeSelect() {
      this.$refs.SelectAssigneeModal.open();
    },
    handleAssigneeChange(data) {
      const { item } = data;
      if (item.length === 0) {
        this.$message.warning(this.$t("sys.please_select_person"));
        return;
      }
      const { id, name } = item[0];
      this.$set(this.formData, "userId", id);
      this.$set(this.formData, "userName", name);
      this.$refs.SelectAssigneeModal.close();
    },

    handleSelectAssigneeNodeChange(org) {
      return getHmuserPageListwithpermission({
        pageSize: 100000,
        pageNo: 1,
        orgIds: org.id,
        status: 1,
      }).then((res) => {
        return res.data;
      });
    },
    // 选中全部
    handleCheckAllChange(val) {
      if (val) {
        this.formData.processKeys = this.processList.map((item) => {
          return item.key;
        });
      }
      this.isIndeterminate = false;
    },
    handleCheckedProcessChange(value) {
      const checkedCount = value.length;
      this.checkAll = checkedCount === this.processList.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.processList.length;
    },
    async submit() {
      try {
        await this.$refs.form.validate();
        const {
          id,
          dateTimeRange,
          // startAt,
          // endAt,
          processKeys,
          userId,
        } = this.formData;
        const startAt = dateTimeRange[0];
        const endAt = dateTimeRange[1];
        let params = {};
        let request = null;
        if (this.isNew) {
          params = { startAt, endAt, processKeys, userId };
          request = postHmtaskdelegate;
        } else {
          params = { id, startAt, endAt, processKeys, userId };
          request = putHmtaskdelegate;
        }
        for (const key in params) {
          params[key] =
            typeof params[key] === "string" ? params[key].trim() : params[key];
        }
        request(params).then((id) => {
          this.showVisible = false;
          this.$emit("reset");
        });
      } catch (error) {}
    },
    handleCancel() {
      this.showVisible = false;
      this.formData = { processKeys: [] };
    },
  },
};
</script>

<style lang="scss" scoped>
.limit {
  max-width: 500px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  display: inline-block;
}
span {
  vertical-align: middle;
}
</style>
